<template>
  <div class="content">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item 
      label="盘点名" 
      prop="orderName" 
      class="front-input"
      :rules="{
              required: true,
              message: '盘点名不能为空',
              trigger: 'blur',
            }"
      >
        <el-input v-model="form.orderName" placeholder="请输入盘点名" />
      </el-form-item>
      <el-row v-for="(domain, index) in form.labidList" :key="index">
        <el-col :span="6">
          <el-form-item 
            class="front-input"
            label="仓库"
            :prop="`labidList[${index}].warehouseId`"
            :rules="{
              required: true,
              message: '仓库不能为空',
              trigger: 'blur',
            }"
          >
            <el-select v-model="form.labidList[index].warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange(index)">
              <el-option v-for="warehouse in warehouses" :key="warehouse.warehouseId" :value="warehouse.warehouseId" :label="warehouse.warehouseName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="form.labidList[index].showStorage">
          <el-form-item 
            class="front-input"
            label="仓位" 
            :prop="'labidList[' + index + '].storageId'"
          >
            <el-select v-model="form.labidList[index].storageId" placeholder="请选择仓位" @change="handleStorageChange(index)">
              <el-option v-for="storage in form.labidList[index].storageOptions" :key="storage.id" :value="storage.id" :label="storage.storageName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="danger" @click="removeDomain(index)">删除</el-button>
        </el-col>
      </el-row>
      <el-form-item prop="term" class="front-input">
        <template #label="scope">
          <span>备注</span>
          <el-tooltip class="item" effect="dark" content="提示：输入样例 2021-2022-1 、2021-2022-2 一定是这个格式！！ " placement="top">
            <i class="el-icon-question" style="font-size: 14px; float: right;"></i>
          </el-tooltip>
        </template>
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">添加盘点单</el-button>
      <el-button @click="addDomain">新增实验室分配</el-button>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from "vue";
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getRelations, createCheckOrder } from '@/api/inbound/inbound';
import { useRouter } from "vue-router"
import { useStore } from 'vuex';
import { useRoute } from "vue-router";
export default defineComponent({
  name: "HomeView",
  setup() {
    const router = useRouter()
    const store = useStore()

    const formRef = ref(null);
    const form = reactive({
      orderName: null,
      remark: null,
      labidList: [
        {
          warehouseId: null,
          storageId: null,
          storageOptions: [],
          showStorage: false
        }
      ]
    });

    const warehouses = ref([]);
    const storageOptions = ref([]);

    const addDomain = () => {
      form.labidList.push({
        warehouseId: null,
        storageId: null,
        storageOptions: [],
        showStorage: false
      });
    };

    const removeDomain = (index) => {
      if (form.labidList.length > 1) {
        form.labidList.splice(index, 1);
      }
    };

    const handleWarehouseChange = (index) => {
      const selectedWarehouse = warehouses.value.find(w => w.warehouseId === form.labidList[index].warehouseId);
      if (selectedWarehouse) {
        form.labidList[index].storageOptions = selectedWarehouse.storageIdList;
        form.labidList[index].showStorage = selectedWarehouse.storageIdList.length > 0;
        form.labidList[index].storageId = null; // 清空之前选择的仓位
      } else {
        form.labidList[index].storageOptions = [];
        form.labidList[index].showStorage = false;
      }
    };

    const handleStorageChange = (index) => {
      const selectedStorageId = form.labidList[index].storageId;
      if (selectedStorageId) {
        validateSelection(index, 'storage');
      }
    };

    const findParentIds = (id, storageList) => {
      const ids = [];
      let currentId = id;
      while (currentId) {
        const currentStorage = storageList.find(s => s.id === currentId);
        if (currentStorage) {
          currentId = currentStorage.parentStorage;
          if (currentId) {
            ids.push(currentId);
          }
        } else {
          break;
        }
      }
      return ids;
    };

    const findChildIds = (id, storageList) => {
      const ids = [];
      const findChildren = (parentStorage) => {
        storageList.forEach(storage => {
          if (storage.parentStorage === parentStorage) {
            ids.push(storage.id);
            findChildren(storage.id);
          }
        });
      };
      findChildren(id);
      return ids;
    };

    const validateSelection = (index, type) => {
      const selectedWarehouseId = form.labidList[index].warehouseId;
      const selectedStorageId = form.labidList[index].storageId;
      const selectedIds = [];

      if (type === 'warehouse') {
        selectedIds.push(selectedWarehouseId);
      } else if (type === 'storage') {
        selectedIds.push(selectedStorageId);
        const parentStorages = findParentIds(selectedStorageId, storageOptions.value);
        const childIds = findChildIds(selectedStorageId, storageOptions.value);
        selectedIds.push(...parentStorages, ...childIds);
      }

      for (let i = 0; i < form.labidList.length; i++) {
        if (i !== index) {
          const otherWarehouseId = form.labidList[i].warehouseId;
          const otherStorageId = form.labidList[i].storageId;

          if (selectedIds.includes(otherWarehouseId) || selectedIds.includes(otherStorageId)) {
            ElMessage.error("已选择过更上级或更下级仓位，请重新选择");
            if (type === 'warehouse') {
              form.labidList[index].warehouseId = null;
            } else if (type === 'storage') {
              form.labidList[index].storageId = null;
            }
            return;
          }
        }
      }
    };

    const validateFormBeforeSubmit = () => {
      const warehouseWithStorages = new Map();
      form.labidList.forEach((item, index) => {
        if (item.warehouseId && item.storageId) {
          if (!warehouseWithStorages.has(item.warehouseId)) {
            warehouseWithStorages.set(item.warehouseId, []);
          }
          warehouseWithStorages.get(item.warehouseId).push(index);
        }
      });

      for (let i = 0; i < form.labidList.length; i++) {
        const item = form.labidList[i];
        if (item.warehouseId && !item.storageId && warehouseWithStorages.has(item.warehouseId)) {
          ElMessage.error("已选了该仓库底下的其它仓位，不能再只选仓库");
          return false;
        }
      }
      return true;
    };

    const submitForm = () => {
    if (!validateFormBeforeSubmit()) {
        return;
    }
    formRef.value.validate((valid) => {
        if (valid) {
            const params = {
                orderName: form.orderName,
                remark: form.remark,
                targetList: form.labidList.map(item => ({
                    warehouseId: item.warehouseId,
                    storageId: item.storageId
                }))
            };
            createCheckOrder(params).then(res => {
                if (res.code === 200) {
                    let createdId;
                    if (res.data && typeof res.data === 'number') {
                        createdId = res.data;
                    } else if (res.data && typeof res.data === 'object' && res.data.hasOwnProperty('id')) {
                        createdId = res.data.id;
                    } else {
                        console.error('无法确定 ID 的来源');
                        return;
                    }
                    console.log('id:', createdId);
                    // 创建成功后触发“继续盘点”操作
                    const value = { id: createdId, orderName: form.orderName, canEdit: true };
                    const newRoute = {
                        path: '/checklist/edit',
                        name: 'CheckEdit',
                        component: () => import('@/views/inbound/checklist/edit.vue'),
                        meta: {
                            keepAlive: true,
                            title: "继续盘点",
                            isDynamic: true,
                            query: value
                        }
                    };
                    // 添加路由到路由器
                    router.addRoute(newRoute);
                    const newTag = {
                        path: '/checklist/edit',
                        title: '继续盘点',
                        query: value
                    };
                    router.push({ path: newRoute.path, query: value });
                    store.commit('addTag', newTag);
                    // 如果在浏览器环境中，关闭当前页面
                    if (typeof window!== 'undefined') {
                        window.close();
                    } else {
                        console.error('Not in a browser environment. Unable to close the page.');
                    }
                } else {
                    ElMessage.error("盘点单创建失败，所选仓库盘点中!");
                }
            });
        } else {
            ElMessage.error("表单验证失败");
        }
    });
};
    /** 路由界面跳转 */
    const jumpRoute = (value) => {
      // 因为是临时路由，你不创建就没有
      // 创建新的路由配置
      const newRoute = {
        path: '/checklist/edit',
        name: 'CheckEdit',
        component: () => import('@/views/inbound/checklist/edit.vue'),
        meta: {
          keepAlive: true,
          title: "查看盘点",
          isDynamic: true,
          query: value
        } 
      };
      // 添加路由到路由器
      router.addRoute(newRoute);
      const newTag = {
        path: '/checklist/edit',
        title: '查看盘点',
        query: value
      };
      // 跳转并传递查询参数
      // router.push({ path: newTag.path, query: { id: 123, name: 'test' } });
      router.push({ path: newTag.path, query: value});
      store.commit('addTag', newTag);
      
    }

    onBeforeMount(() => {
      getRelations().then((res) => {
        warehouses.value = res.data;
        res.data.forEach(warehouse => {
          if (warehouse.storageIdList) {
            warehouse.storageIdList.forEach(storage => {
              storageOptions.value.push(storage);
            });
          }
        });
      });
    });

    return {
      form, formRef,
      handleWarehouseChange,
      handleStorageChange,
      addDomain,
      removeDomain,
      warehouses,
      jumpRoute,
      validateSelection,
      validateFormBeforeSubmit,
      submitForm
    };
  }
});
</script>

<style scoped>
.content {
  background-color: #FFF;
  margin-top: 10px;
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.front-input {
  width: 320px;
}
</style>
